//
//  DepredateViewController.m
//  CarHome
//
//  Created by 王建男 on 14-9-17.
//  Copyright (c) 2014年 WJN_work@163.com. All rights reserved.
//

#import "DepredateViewController.h"
#import "DepreTableViewCell.h"
#import "ActiveTableViewCell.h"
#import "DepreModel.h"
#import "ActiveModel.h"
#import "ActiveViewController.h"
#import "DepreViewController.h"
#import "SequenceView.h"
#import "BrandView.h"
#import "CityView.h"
#import "DeliverModel.h"
#import "CityIdModel.h"
#import "SearchBarVC.h"
#import "Db.h"
#import "MMDrawerController.h"
#import "UIViewController+MMDrawerController.h"


NSString *const depreCell = @"cellId";

@interface DepredateViewController ()

@end

@implementation DepredateViewController

- (void)dealloc
{
    [_depre_Array release];
    [_active_Array release];
    [_depre_urlStr release];
    [_dbArray release];
    _dbArray = nil;
    _depre_urlStr = nil;
    _depre_Array = nil;
    _active_Array = nil;
    [super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        //降价数组
        _depre_Array = [[NSMutableArray alloc] init];
        //活动数组
        _active_Array = [[NSMutableArray alloc] init];
        //数据库数组
        _dbArray = [[NSMutableArray alloc] init];
        _depre_urlStr = [[NSMutableString alloc] init];
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.barTintColor = myColor_dark;
    self.tabBarController.tabBar.barTintColor = myColor_dark;//tabBar颜色
//    self.tabBarController.tabBar.translucent = NO;//tabBar不透明
    // Do any additional setup after loading the view.
    [self createScroll];
    [self createDepre];
    [self createActive];
    //左按钮
    UIButton *buttonLeft_rec_navBar = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonLeft_rec_navBar.frame = CGRectMake(0, 0, 50, 45);
    [buttonLeft_rec_navBar setImage:[UIImage imageNamed: @"Nav_User.png"] forState:UIControlStateNormal];
    [buttonLeft_rec_navBar addTarget:self action:@selector(navLeft:) forControlEvents:UIControlEventTouchUpInside];
    buttonLeft_rec_navBar.imageEdgeInsets = UIEdgeInsetsMake(-2, -15, 2, 15);
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:buttonLeft_rec_navBar];
    
    //中间seg
    NSArray *arr = @[@"降价", @"活动"];
    _seg = [[UISegmentedControl alloc] initWithItems:arr];
    //字体大小
    UIFont *font = [UIFont boldSystemFontOfSize:18.0f];
    NSDictionary *attributes = [NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
    [_seg setTitleTextAttributes:attributes
                               forState:UIControlStateNormal];
    [_seg setTintColor:[UIColor whiteColor]];//颜色
    [_seg setWidth:80 forSegmentAtIndex:0];
    [_seg setWidth:80 forSegmentAtIndex:1];
    _seg.selectedSegmentIndex = 0;
    [self.view bringSubviewToFront:_depre_View];
    [_seg addTarget:self action:@selector(segAction:) forControlEvents:UIControlEventValueChanged];
    [self.navigationItem setTitleView:_seg];
    //searchbar
    UIButton *buttonRight_rec_navBar = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonRight_rec_navBar.frame = CGRectMake(0, 5, 50, 30);
    [buttonRight_rec_navBar setImage:[UIImage imageNamed:@"Depre_SearchButton.png"] forState:UIControlStateNormal];
    [buttonRight_rec_navBar addTarget:self action:@selector(navRight:) forControlEvents:UIControlEventTouchUpInside];
    buttonRight_rec_navBar.imageEdgeInsets = UIEdgeInsetsMake(-2, 15, 2, -15);
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:buttonRight_rec_navBar];
    
    //降价网络请求
    [self connect:[NSString stringWithFormat:DepreURL, (long)self.provinceId, (long)self.cityId,(long)self.value, (long)self.carId, (long)self.fctId, (long)self.specId, a]];
    //活动网络请求
    NSInteger c = 110100;
    [self conncetion:[NSString stringWithFormat:ActiveURL, (long)c]];
    //完整选择消息中心
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getMessage:) name:@"center" object:nil];
    //车系消息中心
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getCheXi:) name:@"chexi" object:nil];
    //车型消息中心
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getCheXing:) name:@"chexing" object:nil];
    //城市消息中心
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getChengShi:) name:@"chengshi" object:nil];
}

#pragma mark -
#pragma mark nav左侧点击事件
- (void)navLeft:(id)sender
{
    //左抽屉
    [self.tabBarController.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}

#pragma mark -
#pragma mark 消息中心方法

//完整选择消息中心

- (void)getMessage:(NSNotification *)obj
{
    [_depre_Array removeAllObjects];
    DeliverModel *model = obj.object;
    self.carId = model.carId;
    self.fctId = model.fctId;
    self.specId = model.specId;
    a = 1;
    [self connect:[NSString stringWithFormat:DepreURL, (long)self.provinceId, (long)self.cityId,(long)self.value, (long)self.fctId, (long)self.specId, (long)self.carId, a]];
    [_depre_Table reloadData];
}
//车系消息中心

- (void)getCheXi:(NSNotification *)obj
{
    [_depre_Array removeAllObjects];
    DeliverModel *model = obj.object;
    self.fctId = model.fctId;
    self.specId = 0;
    self.carId = 0;
    a = 1;
    [self connect:[NSString stringWithFormat:DepreURL, (long)self.provinceId, (long)self.cityId,(long)self.value, (long)self.fctId, (long)self.specId, (long)self.carId, a]];
    [_depre_Table reloadData];
}
//车型消息中心

- (void)getCheXing:(NSNotification *)obj
{
    [_depre_Array removeAllObjects];
    DeliverModel *model = obj.object;
    self.fctId = model.fctId;
    self.specId = model.specId;
    self.carId = 0;
    a = 1;
    [self connect:[NSString stringWithFormat:DepreURL, (long)self.provinceId, (long)self.cityId,(long)self.value, (long)self.fctId, (long)self.specId, (long)self.carId, a]];
    [_depre_Table reloadData];
}
//城市消息中心

- (void)getChengShi:(NSNotification *)obj
{
    [_depre_Array removeAllObjects];
    [_active_Array removeAllObjects];
    CityIdModel *city = obj.object;
    self.provinceId = city.provinceId;
    self.cityId = city.cityId;
    UIButton *button = (UIButton *)[self.view viewWithTag:101];
    [button setTitle:city.cityname forState:UIControlStateNormal];
    [_button setTitle:city.cityname forState:UIControlStateNormal];
    [self connect:[NSString stringWithFormat:DepreURL, (long)self.provinceId, (long)self.cityId,(long)self.value, (long)self.fctId, (long)self.specId, (long)self.carId, a]];
    [self conncetion:[NSString stringWithFormat:ActiveURL, (long)self.cityId]];
    [_depre_Table reloadData];
    [_active_Table reloadData];
}

#pragma mark -
#pragma mark seg点击

//seg点击事件
- (void)segAction:(id)sender
{
    /********
     *0.当seg选择降价时
     *1.当seg选择活动时
     */
    switch (_seg.selectedSegmentIndex) {
        case 0:
            [_scroll setContentOffset:CGPointMake(0, 0) animated:YES];
            [_scroll bringSubviewToFront:_depre_View];
            break;
        case 1:
            [_scroll setContentOffset:CGPointMake(320, 0) animated:YES];
            [_scroll bringSubviewToFront:_active_View];
            break;
        default:
            break;
    }
}

#pragma mark -
#pragma mark nav右侧搜索功能

- (void)navRight:(id)sender
{
    SearchBarVC *search = [[SearchBarVC alloc] init];
    [self presentViewController:search animated:YES completion:^{
        
    }];
    [search release];
}


#pragma mark -
#pragma mark 创建UIScrollView

- (void)createScroll
{
    _scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height - 64 )];
    _scroll.delegate = self;
    _scroll.contentSize = CGSizeMake(640, self.view.frame.size.height - 64 - 49);
    _scroll.bounces = NO;
    _scroll.showsHorizontalScrollIndicator = NO;
    _scroll.pagingEnabled = YES;
    [self.view addSubview:_scroll];
}

#pragma mark - 
#pragma mark UIScrollView协议

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (_scroll.contentOffset.x == 320) {
        _seg.selectedSegmentIndex = 1;
    } else {
        _seg.selectedSegmentIndex = 0;
    }
}

#pragma mark -
#pragma mark 降价界面

//降价
- (void)createDepre
{
   
    //heard for tableview
    _depre_heardView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
    _depre_heardView.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.95];
    for (int i = 0; i < 3; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setFrame:CGRectMake(100 * i + 10, 0, 100, 30)];
        button.tag = 100 + i;
        NSArray * arr = @[@" 品牌", @" 全国", @" 排序"];
        [button setTitle:[arr objectAtIndex:i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"Depredate_DrawerButton.png"] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_depre_heardView addSubview:button];
    }
    //tableview
    _depre_View = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64 )];
    [_depre_View addSubview:_depre_heardView];
    [_scroll addSubview:_depre_View];
    _depre_Table = [[UITableView alloc] initWithFrame:CGRectMake(0, 30, _depre_View.frame.size.width, _depre_View.frame.size.height - 30) style:UITableViewStylePlain];
    [_depre_Table setSeparatorColor:[UIColor clearColor]];
    _depre_Table.dataSource = self;
    _depre_Table.delegate = self;
    [_depre_Table registerClass:[DepreTableViewCell class] forCellReuseIdentifier:depreCell];
    [_depre_View addSubview:_depre_Table];
    [self setupDepreRefresh];
    [_depre_Table release];
    
}

#pragma mark -
#pragma mark 降价界面按钮点击事件

- (void)buttonAction:(id)sender
{
    /******************
     *button.tag == 100当点击品牌按钮
     *button.tag == 101当点击城市按钮
     *button.tag == 102当点击排序按钮
     ******************/
    
    UIButton *button = (UIButton *)sender;
    if (button.tag == 100) {
        BrandView *brand = [[BrandView alloc] initWithFrame:CGRectMake(0, 20, 320, self.view.frame.size.height + 64 + 49)];
        brand.block = ^(){
            [_depre_Array removeAllObjects];
            [brand removeFromSuperview];
            self.fctId = 0;
            self.specId = 0;
            self.carId = 0;
            a = 1;
            [self connect:[NSString stringWithFormat:DepreURL, (long)self.provinceId, (long)self.cityId, (long)self.value, (long)self.fctId, (long)self.specId, (long)self.carId, a]];
            [_depre_Table reloadData];
        };
        [self.tabBarController.view addSubview:brand];
        [_bgView removeFromSuperview];
        [brand release];
    } else if (button.tag == 101) {
        CityView *city = [[CityView alloc] initWithFrame:CGRectMake(0, 20, 320, self.view.frame.size.height + 64 + 49)];
        city.block = ^(){
            [_depre_Array removeAllObjects];
            NSInteger z = 0;
            [self connect:[NSString stringWithFormat:DepreURL, (long)z, (long)z, (long)self.value, (long)self.fctId, (long)self.specId, (long)self.carId, a]];
            UIButton *button = (UIButton *)[self.view viewWithTag:101];
            [button setTitle:@"全国" forState:UIControlStateNormal];
            [city removeFromSuperview];
            [_depre_Table reloadData];
        };
        [self.tabBarController.view addSubview:city];
        [_bgView removeFromSuperview];
        [city release];
    } else if (button.tag == 102) {
        SequenceView *sequence = [[SequenceView alloc] initWithFrame:CGRectMake(0, 20, 320, self.view.frame.size.height + 64 + 49)];
        [sequence sendUrl:^(DeliverModel *model) {
            [_depre_Array removeAllObjects];
            self.value = model.value;
            [self connect:[NSString stringWithFormat:DepreURL, (long)self.provinceId, (long)self.cityId, (long)self.value, (long)self.fctId, (long)self.specId, (long)self.carId, a]];
            [_depre_Table reloadData];
        }];
        [self.tabBarController.view addSubview:sequence];
        [_bgView removeFromSuperview];
        [sequence release];
    }
}

#pragma mark -
#pragma mark 活动界面

//活动
- (void)createActive
{
    //heard for tableview
    _active_heardView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 30)];
    _active_heardView.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.95];
    _button = [UIButton buttonWithType:UIButtonTypeCustom];
    [_button setFrame:CGRectMake(0, 0, 80, 30)];
    [_button setTitle:@"北京" forState:UIControlStateNormal];
    [_button setImage:[UIImage imageNamed:@"Depredate_DrawerButton.png"] forState:UIControlStateNormal];
    [_button addTarget:self action:@selector(activeButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_active_heardView addSubview:_button];
    //tableview
    _active_View = [[[UIView alloc] initWithFrame:CGRectMake(320, 0, self.view.frame.size.width, self.view.frame.size.height - 64 )] autorelease];
    [_active_View addSubview:_active_heardView];
    [_scroll addSubview:_active_View];
    _active_Table = [[UITableView alloc] initWithFrame:CGRectMake(0, 30, _active_View.frame.size.width, _active_View.frame.size.height - 30) style:UITableViewStylePlain];
    _active_Table.separatorColor = [UIColor clearColor];
    _active_Table.dataSource = self;
    _active_Table.delegate = self;
    [_active_Table registerClass:[ActiveTableViewCell class] forCellReuseIdentifier:depreCell];
    [_active_View addSubview:_active_Table];
    [self setupAcitveRefresh];
    [_active_Table release];
}

#pragma mark -
#pragma mark 活动界面按钮点击事件

- (void)activeButtonAction:(id)sender
{
    CityView *city = [[CityView alloc] initWithFrame:CGRectMake(0, 20, 320, self.view.frame.size.height + 64 + 49)];
    [self.tabBarController.view addSubview:city];
    city.block = ^(){
        [city removeFromSuperview];
        [_button setTitle:@"全国" forState:UIControlStateNormal];
    };
    [city release];
}

#pragma mark -
#pragma mark UITableViewDataSource协议

//每个section行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //判断该页面是降价还是活动
    if (tableView == _depre_Table) {
        return [_depre_Array count];
    } else if (tableView == _active_Table) {
        return [_active_Array count];
    }
    return 0;
}

//重用机制
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //判断该页面是降价还是活动
    if (tableView == _depre_Table) {
        DepreTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:depreCell forIndexPath:indexPath];
        DepreModel *model = [_depre_Array objectAtIndex:indexPath.row];
        [cell setCarUrl:model.specpic name:model.seriesname type:model.specname depre:model.fctprice price:model.dealerprice city:model.car.city shop:model.car.shortname sell:model.car.orderrange typeUrl:model.styledinventorystate];
        return cell;
    }  else if (tableView == _active_Table) {
        ActiveTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:depreCell forIndexPath:indexPath];
        ActiveModel *model = [_active_Array objectAtIndex:indexPath.row];
        [cell setUrl:model.imageUrl title:model.title cityName:model.cityName regenddate:model.regenddate pcviews:model.pcviews];
        return cell;
    }
    return nil;
}

#pragma mark -
#pragma mark UITableViewDelegate协议

//行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //判断该页面是降价还是活动
    if (tableView == _depre_Table) {
        return 110;
    } else if (tableView == _active_Table) {
        return 270;
    }
    return 0;
}

//cell点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //判断该页面是降价还是活动
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (tableView == _depre_Table) {
        DepreModel *model = [_depre_Array objectAtIndex:indexPath.row];
        [self seleteAll];
        [self insertWithModel:model];
        DepreViewController *depre = [[DepreViewController alloc] init];
        [depre setWebUrl:[NSString stringWithFormat:@"http://cont.app.autohome.com.cn/autov4.2/content/dealer/downprice-a1-pm2-v4.2.0-sp%@-n%@-t%@-d%@-ss%@-nt%@.html", model.specid, model.articleid, model.articletype, model.car.carId, model.seriesid, model.car.ispromotion]];
        [self.navigationController pushViewController:depre animated:YES];
        [depre release];
    } else if (tableView == _active_Table) {
        ActiveModel *model = [_active_Array objectAtIndex:indexPath.row];
        ActiveViewController *active = [[ActiveViewController alloc] init];
        [active setWebUrl:model.jumpUrl];
        [self.navigationController pushViewController:active animated:YES];
        [active release];
    }
}

#pragma mark -
#pragma mark 数据库查询

- (void)seleteAll
{
    sqlite3 *db = [Db openDataBase];
    [_dbArray removeAllObjects];
    //制作sqlite替身
    sqlite3_stmt *stmt = nil;
    //数据库语句
    NSString *sqlStr = [NSString stringWithFormat:@"select * from browse"];
    //根据数据库语句将从db中查询到内容赋值给替身(-1代表无限长)
    int result = sqlite3_prepare_v2(db, [sqlStr UTF8String], -1, &stmt, nil);
    //定义数组存储所有数据信息
    if (result == SQLITE_OK) {
        //根据stmt中内容逐条获取数据
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            //把每条数据的每一个列取出来
//            int carId = sqlite3_column_int(stmt, 0);
            const unsigned char *carImg = sqlite3_column_text(stmt, 1);
            const unsigned char *carName = sqlite3_column_text(stmt, 2);
            const unsigned char *carTypename = sqlite3_column_text(stmt, 3);
            float carDepre = sqlite3_column_double(stmt, 4);
            float carPrice = sqlite3_column_double(stmt, 5);
            const unsigned char *carCity = sqlite3_column_text(stmt, 6);
            const unsigned char *carShop = sqlite3_column_text(stmt, 7);
            const unsigned char *carSell = sqlite3_column_text(stmt, 8);
            const unsigned char *carType = sqlite3_column_text(stmt, 9);
            const unsigned char *carSpecid = sqlite3_column_text(stmt, 10);
            const unsigned char *carArticleid = sqlite3_column_text(stmt, 11);
            const unsigned char *carArticletype = sqlite3_column_text(stmt, 12);
            const unsigned char *carid = sqlite3_column_text(stmt, 13);
            const unsigned char *carSeriesid = sqlite3_column_text(stmt, 14);
            const unsigned char *carIspromotion = sqlite3_column_text(stmt, 15);
            //将const 转换为nsstring
            NSString *car_img = [NSString stringWithUTF8String:(const char *)carImg];
            NSString *car_name = [NSString stringWithUTF8String:(const char *)carName];
            NSString *car_typename = [NSString stringWithUTF8String:(const char *)carTypename];
            CGFloat car_depre = carDepre;
            CGFloat car_price = carPrice;
            NSString *car_city = [NSString stringWithUTF8String:(const char *)carCity];
            NSString *car_shop = [NSString stringWithUTF8String:(const char *)carShop];
            NSString *car_sell = [NSString stringWithUTF8String:(const char *)carSell];
            NSString *car_type = [NSString stringWithUTF8String:(const char *)carType];
            NSString *car_specid = [NSString stringWithUTF8String:(const char *)carSpecid];
            NSString *car_articleid = [NSString stringWithUTF8String:(const char *)carArticleid];
            NSString *car_articletype = [NSString stringWithUTF8String:(const char *)carArticletype];
            NSString *car_carid = [NSString stringWithUTF8String:(const char *)carid];
            NSString *car_seriesid = [NSString stringWithUTF8String:(const char *)carSeriesid];
            NSString *car_ispromotion = [NSString stringWithUTF8String:(const char *)carIspromotion];
            DepreModel *model = [DepreModel depreModelWithimg:car_img name:car_name typename:car_typename depre:car_depre price:car_price city:car_city shop:car_shop sell:car_sell type:car_type specid:car_specid articleid:car_articleid articletype:car_articletype carid:car_carid seriesid:car_seriesid ispromotion:car_ispromotion];
            [_dbArray addObject:model];
        }
    }
    //清除替身
    sqlite3_finalize(stmt);
    
}

#pragma mark -
#pragma mark 数据库插入

-(void)insertWithModel:(DepreModel *)model
{
    /*1.获得数据库指针对象
     *2.书写数据库语句
     *3.执行数据库语句
     */
    //1.
    sqlite3 *db = [Db openDataBase];
    //2.
    NSString *sqlStr = [NSString stringWithFormat:@"insert into browse (car_id,car_img,car_name,car_typename,car_depre,car_price,car_city,car_shop,car_sell,car_type,car_specid,car_articleid,car_articletype,car_carid,car_seriesid,car_ispromotion) values (%ld,'%@','%@','%@',%f,%f,'%@','%@','%@','%@','%@','%@','%@','%@','%@','%@')", (unsigned long)[_dbArray count], model.specpic, model.seriesname, model.specname, model.dealerprice, model.fctprice, model.car.city, model.car.shortname, model.car.orderrange, model.styledinventorystate, model.specid, model.articleid, model.articletype, model.car.carId, model.seriesid, model.car.ispromotion];
    //3.
    int result = sqlite3_exec(db, [sqlStr UTF8String], nil, nil, nil);
    if (result == SQLITE_OK) {
        
    } else {
        
    }
    
}


#pragma mark -
#pragma mark 降价网络请求

- (void)connect:(NSString *)url
{
    [NetUrl connect:url parmater:nil Block:^(NSData *data) {
        NSMutableDictionary *dic = (NSMutableDictionary *)data;
        NSMutableDictionary *dict = [dic objectForKey:@"result"];
        NSMutableArray * car = [dict objectForKey:@"carlist"];
        for (NSMutableDictionary *dic in car) {
            DepreModel *model = [[DepreModel alloc] init];
            model.specid = [dic objectForKey:@"specid"];
            model.articleid = [dic objectForKey:@"articleid"];
            model.articletype = [dic objectForKey:@"articletype"];
            model.seriesid = [dic objectForKey:@"seriesid"];
            model.car.carId= [[dic objectForKey:@"dealer"] objectForKey:@"id"];
            model.car.ispromotion = [[dic objectForKey:@"dealer"] objectForKey:@"ispromotion"];
            model.inventorystate = [dic objectForKey:@"inventorystate"];
            model.seriesname = [dic objectForKey:@"seriesname"];
            model.specname = [dic objectForKey:@"specname"];
            model.dealerprice = [[dic objectForKey:@"dealerprice"] floatValue];
            model.fctprice = [[dic objectForKey:@"fctprice"] floatValue];
            model.specpic = [dic objectForKey:@"specpic"];
            model.styledinventorystate = [dic objectForKey:@"styledinventorystate"];
            model.car.city = [[dic objectForKey:@"dealer"]objectForKey:@"city"];
            model.car.shortname = [[dic objectForKey:@"dealer"]objectForKey:@"shortname"];
            model.car.orderrange = [[dic objectForKey:@"dealer"]objectForKey:@"orderrange"];
            [_depre_Array addObject:model];
        }
        [_depre_Table headerEndRefreshing];
        [_depre_Table footerEndRefreshing];
        [_depre_Table reloadData];
        if ([_depre_Array count] == 0) {
            _bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 30, self.view.frame.size.width, self.view.frame.size.height - 30)];
            _bgView.backgroundColor = [UIColor whiteColor];
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 200, 320, 80)];
            [label setText:@"暂无降价活动"];
            label.textAlignment = NSTextAlignmentCenter;
            [_bgView addSubview:label];
            [_depre_View addSubview:_bgView];
        }
    }];
    
}

#pragma mark -
#pragma mark 活动网络请求

- (void)conncetion:(NSString *)url
{
    [NetUrl connect:url parmater:nil Block:^(NSData *data) {
        NSMutableDictionary *dic = (NSMutableDictionary *)data;
        NSMutableDictionary *dict = [dic objectForKey:@"result"];
        NSMutableArray *active = [dict objectForKey:@"activitylist"];
        for (NSMutableDictionary *dic in active) {
            ActiveModel *model = [[ActiveModel alloc] init];
            model.imageUrl = [dic objectForKey:@"imgpath"];
            model.jumpUrl = [dic objectForKey:@"url"];
            model.title = [dic objectForKey:@"title"];
            model.cityName = [dic objectForKey:@"cityname"];
            model.regenddate = [dic objectForKey:@"regenddate"];
            model.pcviews = [[dic objectForKey:@"pcviews"] intValue];
            [_active_Array addObject:model];
            [_active_Table reloadData];
        }
    }];
}

#pragma mark -
#pragma mark 降价setRefresh上拉加载 下拉刷新

- (void)setupDepreRefresh
{
    [_depre_Table addHeaderWithTarget:self action:@selector(headerDepreRereshing)];
    
//    [_depre_Table headerBeginRefreshing]; //程序开始即刷新
    
    [_depre_Table addFooterWithTarget:self action:@selector(footerDepreRereshing)];
    _depre_Table.headerPullToRefreshText = @"下拉刷新";
    _depre_Table.headerReleaseToRefreshText = @"释放刷新";
    _depre_Table.headerRefreshingText = @"正在刷新中···";
    _depre_Table.footerPullToRefreshText = @"上拉加载";
    _depre_Table.footerReleaseToRefreshText = @"释放加载";
    _depre_Table.footerRefreshingText = @"正在加载中···";
}

- (void)headerDepreRereshing
{
    [_depre_Array removeAllObjects];
    a = 1;
    [self connect:[NSString stringWithFormat:DepreURL, (long)self.provinceId, (long)self.cityId, (long)self.value, (long)self.carId, (long)self.fctId, (long)self.specId, a]];
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [_depre_Table reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_depre_Table headerEndRefreshing];
        
    });
}

static int a = 1;

- (void)footerDepreRereshing
{
    if ([_depre_Array count] >= 20) {
        _depre_urlStr = [NSMutableString stringWithFormat:DepreURL, (long)self.provinceId, (long)self.cityId, (long)self.value, (long)self.fctId, (long)self.specId, (long)self.carId, a] ;
        NSRange subStr = [_depre_urlStr rangeOfString:[NSString stringWithFormat:@"-p%d", a]];
        a++;
        if (subStr.location != NSNotFound) {
            [_depre_urlStr replaceCharactersInRange:subStr withString:[NSString stringWithFormat:@"-p%d", a]];
        }
        [self connect:_depre_urlStr];
        // 2.2秒后刷新表格UI
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [_depre_Table reloadData];
            
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [_depre_Table footerEndRefreshing];
            
        });
    }
}

#pragma mark -
#pragma mark 活动setRefresh下拉刷新

- (void)setupAcitveRefresh
{
    [_active_Table addHeaderWithTarget:self action:@selector(headerActiveRereshing)];
    
//    [_active_Table headerBeginRefreshing]; //程序开始即刷新
    _active_Table.headerPullToRefreshText = @"下拉刷新";
    _active_Table.headerReleaseToRefreshText = @"释放刷新";
    _active_Table.headerRefreshingText = @"正在刷新中···";
}

- (void)headerActiveRereshing
{
    [self conncetion:[NSString stringWithFormat:ActiveURL, (long)self.cityId]];
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [_active_Table reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_active_Table headerEndRefreshing];
        
    });
}

#pragma mark -
#pragma mark 隐藏tabBar

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    [self.tabBarController.tabBar setHidden:YES];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [self.tabBarController.tabBar setHidden:NO];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.tabBarController.tabBar setHidden:YES];
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    [self.tabBarController.tabBar setHidden:NO];
}



- (void)didReceiveMemoryWarning
{
   [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
